
function initMouse() {
    var canvas = document.getElementById("battlefieldCanvas");
    if (canvas.getContext) {
        canvas.onselectstart = function() {
            return false;
        };
        canvas.addEventListener('mousemove', mouseMoveEvent, false);
        canvas.addEventListener('mousedown', mouseDownEvent, false);
        canvas.addEventListener('mouseup', mouseUpEvent, false);
    }
}

function mouseMoveEvent(evt) {
    var player = findEntity(playerId.value);
    if (player === null) {
        return;
    }

    var mousePosition = getMousePos(evt);

    player.angle = getMouseAngleToPlayer(mousePosition);

    updatePlayerAngle(player.angle);
}

function mouseDownEvent(evt) {
    var mousePosition = getMousePos(evt);

    mousedown(evt.button, getMouseAngleToPlayer(mousePosition));
}

function mouseUpEvent(evt) {
    mouseup(evt.button);
}

function getMousePos(evt) {
    var canvas = document.getElementById("battlefieldCanvas");

    var rect = canvas.getBoundingClientRect();
    return {
        x: evt.clientX - rect.left,
        y: evt.clientY - rect.top
    };
}

function getMouseAngleToPlayer(mousePosition) {
    var player = findEntity(playerId.value);
    if (player === null) {
        return 0;
    }

    var mousePositionTransformet = new Vector(0, 0);

    mousePositionTransformet.x = mousePosition.x + player.pos.x - 512;
    mousePositionTransformet.y = mousePosition.y + player.pos.y - 384;

    var direction = mousePositionTransformet.sub(player.pos);

    var playerAngle = Math.atan2(direction.y, direction.x);

    var rotationMatrix = new Matrix();
    rotationMatrix.rotation(playerAngle + Math.PI / 2);

    var weaponPos = rotationMatrix.mulV(new Vector(10, 0));

    weaponPos = weaponPos.add(player.pos);

    var weaponDirection = mousePositionTransformet.sub(weaponPos);

    var angle = Math.atan2(weaponDirection.y, weaponDirection.x);

    return angle;
}